package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.DeviceVo;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-21
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private Client client;


    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    public static final String ALL_PRODUCT_KEY = "iot:all_product";

    /**
     * 查询设备
     *
     * @param deviceDto 设备主键
     * @return 设备
     */
    @Override
    public DeviceVo selectDeviceById(DeviceDto deviceDto) {
        //查询iot平台中的设备数据
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(deviceDto.getIotId());
        queryDeviceDetailRequest.setProductKey(deviceDto.getProductKey());
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse queryDeviceDetailResponse;
        try {
            queryDeviceDetailResponse = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }
        //安全校验
        if (!queryDeviceDetailResponse.getBody().success) {
            throw new RuntimeException("物联网接口 - 查询设备，调用失败");
        }
        //查询表中的数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);

        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = queryDeviceDetailResponse.getBody().getData();
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }


    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDevice(Device device) {
        //先修改本地数据
        try {
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("数据修改失败！");
        }

        //封装待修改的数据
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo DeviceInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        DeviceInfo.setIotId(device.getIotId());
        DeviceInfo.setNickname(device.getNickname());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceList = new ArrayList<>();
        deviceList.add(DeviceInfo);

        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setDeviceNicknameInfo(deviceList);
        BatchUpdateDeviceNicknameResponse batchUpdateDeviceNicknameResponse;
        try {
            batchUpdateDeviceNicknameResponse = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }

        if (!batchUpdateDeviceNicknameResponse.getBody().success) {
            throw new BaseException(batchUpdateDeviceNicknameResponse.getBody().getErrorMessage());
        }
        return 1;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param request 设备主键
     * @return 结果
     */
    @Transactional
    @Override
    public void deleteDevice(DeleteDeviceRequest request) {
        //删除数据库
        try {
            LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Device::getIotId, request.getIotId());
            remove(queryWrapper);
        } catch (Exception e) {
            throw new BaseException("数据删除失败！");
        }

        //删除ito中的设备
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse deleteDeviceResponse;
        try {
            deleteDeviceResponse = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }

        if (!deleteDeviceResponse.getBody().success) {
            throw new BaseException(deleteDeviceResponse.getBody().getErrorMessage());
        }
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(200);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //调用第三方查询产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        //判断，如果数据为空，则中断请求
        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        //存储到redis
        stringRedisTemplate.opsForValue().set(ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //查询redis
        String productListJson = stringRedisTemplate.opsForValue().get(ALL_PRODUCT_KEY);
        return JSONUtil.toList(productListJson, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Transactional
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //导数据库中查询，判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (count(queryWrapper) > 0) {
            throw new BaseException("设备名称重复，请重新输入");
        }
        //iot平台新增数据
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        //查询设备信息
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(deviceDto.getProductKey());
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        if (!queryProductResponse.getBody().success) {
            throw new BaseException(queryProductResponse.getBody().getErrorMessage());
        }

        //存储到数据库
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getBody().getData().getIotId());
        device.setProductName(queryProductResponse.getBody().getData().getProductName());
        //物理位置
        if (device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }
        //补全设备id
        device.setIotId(response.getBody().getData().getIotId());
        try {
            save(device);
        } catch (Exception e) {
            //删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setProductKey(device.getProductKey());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            DeleteDeviceResponse deleteDeviceResponse;
            try {
                deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("物联网接口 - 删除设备，调用失败");
            }
            if (!deleteDeviceResponse.getBody().success) {
                throw new BaseException(deleteDeviceResponse.getBody().getErrorMessage());
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse;
        try {
            queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }
        if (!queryDevicePropertyStatusResponse.getBody().success) {
            throw new BaseException(queryDevicePropertyStatusResponse.getBody().getErrorMessage());
        }
        //封装数据返回
        return AjaxResult.success(queryDevicePropertyStatusResponse.getBody().getData());
    }

    /**
     * 查询物模型发布状态详细信息
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }
}
